package rs.networx.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import rs.networx.dao.FriendRequestDao;
import rs.networx.dao.PersonDao;
import rs.networx.entity.Person;
import rs.networx.util.ErrorMessages;

//------------------------------------------------------------------------------------------------------------------------------------------------------
public class SendFriendRequestServletMembers extends HttpServlet {

	private static final long serialVersionUID = -8916795839575147177L;

	@EJB
	private PersonDao personDao;

	@EJB
	private FriendRequestDao friendRequestDao;

	private String username;
	private String password;
	private Integer intLoggedUserID;
	private Person loggedUser;

	private String selectedPersonID;
	private Integer intSelectedPersonID;
	private Person selectedPerson;

	private String targetPersonID;
	private Integer intTargetPersonID;

	private Set<Person> personsFriends;
	private Set<Person> loggedUsersFriends;

	private ArrayList<Person> personsFriendsList;
	private ArrayList<Person> loggedUsersFriendsList;

	private ArrayList<Person> youAreFriends;
	private ArrayList<Person> youAreNotFriends;
	private List<Person> resultLicniProfiliKojimaSamPoslaoZahtevZaPrijateljstvo;

	private boolean pass;

	//-------------------------------------------------------------------------------------------------------------------------------------------------
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		System.out.println("*** Loaded SendFriendRequestServlet ***");

		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());

		HttpSession session = request.getSession();
		loggedUser = (Person)session.getAttribute("logovaniUser");

		// selectedPersonForMembersBrowsing...
		selectedPersonID = request.getParameter("personID");

		// osoba kojoj saljemo friend request...
		targetPersonID = request.getParameter("targetID");

		try {	
			System.out.println("selectedPersonID: " + selectedPersonID);

			intSelectedPersonID = Integer.parseInt(selectedPersonID);
			System.out.println("intSelectedPersonID: " + intSelectedPersonID);

			System.out.println("targetPersonID: " + targetPersonID);
			intTargetPersonID = Integer.parseInt(targetPersonID);
			System.out.println(intTargetPersonID + "  " + intTargetPersonID);

			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			intLoggedUserID = loggedUser.getId();

			System.out.println(username + "  " + password + "  " + intLoggedUserID);
		} catch (Exception e) {
			//e.printStackTrace();
		}

		if(intSelectedPersonID != null){
			// sada na osnovu intSelectedPersonID treba da nadjemo datog selectedPerson-a(selectedPersonForMembersBrowsing)...
			selectedPerson = personDao.findById(intSelectedPersonID);
			System.out.println("selectedPersonForMembersBrowsing: " + selectedPerson);

			if(loggedUser != null){
				if(selectedPerson != null){
					if(intTargetPersonID != null){

						// data funkcija personDao.addFriendRequest() dodaje notifikaciju za onoga kome saljemo friend request(target person)... 
						// isto tako, dodaje i notifikaciju za logged usera da je poslao friend request target personu...
						// isto tako, dodaje i po notifikaciju za svakog prijatelja target persona(onoga kome saljemo friend request)...
						// da logged user zeli da bude prijatelj sa njim...
						// isto tako, dodaje i po notifikaciju za svakog prijatelja logged usera(onoga koji salje friend request)...
						// da logged user zeli da bude prijatelj sa target person-om(onaj kome saljemo friend request)...
						pass = personDao.addFriendRequest(intLoggedUserID, intTargetPersonID);

						if(pass){
							// ako je sve proslo ok...
							request.setAttribute("selectedPersonForMembersBrowsing", selectedPerson);

							// filtriramo podatke...
							personsFriends = personDao.getFriends(intSelectedPersonID);

							if(personsFriends != null && personsFriends.size() > 0){
								loggedUsersFriends = personDao.getFriends(intLoggedUserID);

								if(loggedUsersFriends != null && loggedUsersFriends.size() > 0){

									// pretvaramo personsFriends Set u listu personsFriendsList...
									if(personsFriends == null || personsFriends.size() == 0){
										// znaci da nema prijatelja, pa idemo dalje...
										System.out.println("personsFriends: " + personsFriends.size());

									}else if(personsFriends != null && personsFriends.size() > 0){
										personsFriendsList = new ArrayList<Person>();

										@SuppressWarnings("rawtypes")
										Iterator iter = personsFriends.iterator();
										while(iter.hasNext()){
											personsFriendsList.add((Person)iter.next());
										}
										System.out.println("personsFriendsList: " + personsFriendsList.size());
									}

									// pretvaramo loggedUsersFriends Set u listu loggedUsersFriendsList...
									if(loggedUsersFriends == null || loggedUsersFriends.size() == 0){
										// znaci da nema prijatelja, pa idemo dalje...
										System.out.println("loggedUsersFriends: " + loggedUsersFriends.size());

									}else if(loggedUsersFriends != null && loggedUsersFriends.size() > 0){
										loggedUsersFriendsList = new ArrayList<Person>();

										@SuppressWarnings("rawtypes")
										Iterator iter = loggedUsersFriends.iterator();
										while(iter.hasNext()){
											loggedUsersFriendsList.add((Person)iter.next());
										}
										System.out.println("loggedUsersFriendsList: " + loggedUsersFriendsList.size());
									}

									youAreFriends = new ArrayList<Person>();
									youAreNotFriends = new ArrayList<Person>();
									resultLicniProfiliKojimaSamPoslaoZahtevZaPrijateljstvo = new ArrayList<Person>();

									for(int i = 0; i < personsFriendsList.size(); i++){
										if(personsFriendsList.get(i).getId().equals(intLoggedUserID)){
											youAreFriends.add(loggedUser);
											continue;
										}else{
											if(personDao.areFriends(intLoggedUserID, personsFriendsList.get(i).getId()) == true){
												youAreFriends.add(personsFriendsList.get(i));
												continue;
											}else if(personDao.areFriends(intLoggedUserID, personsFriendsList.get(i).getId()) == false){
												if(friendRequestDao.checkIfISentFriendRequest(loggedUser, personsFriendsList.get(i)) == true){
													resultLicniProfiliKojimaSamPoslaoZahtevZaPrijateljstvo.add(personsFriendsList.get(i));
													continue;
												}
												youAreNotFriends.add(personsFriendsList.get(i));
												continue;
											}
										}
									}
								}

								System.out.println("youAreFriends: " + youAreFriends.size());
								System.out.println("youAreNotFriends: " + youAreNotFriends.size());

								request.setAttribute("searchStatusForMembers", ErrorMessages.PERSON_HAVE_FRIENDS);
								request.setAttribute("youAreNotFriends", youAreNotFriends);
								request.setAttribute("youAreFriends", youAreFriends);
								request.setAttribute("resultLicniProfiliKojimaSamPoslaoZahtevZaPrijateljstvo", 
										resultLicniProfiliKojimaSamPoslaoZahtevZaPrijateljstvo);

							}else if(personsFriends == null || personsFriends.size() == 0){

								/*session.setAttribute("searchStatusForMembers", ErrorMessages.PERSON_DO_NOT_HAVE_FRIENDS);*/
								request.setAttribute("searchStatusForMembers", ErrorMessages.PERSON_DO_NOT_HAVE_FRIENDS);
							}

							request.setAttribute("selectedPersonForMembersBrowsing", selectedPerson);

							request.getRequestDispatcher("ViewFriendsForMembers.jsp").forward(request, response);
							return;

						}else if(!pass){
							// ako je doslo do greske...
							request.getRequestDispatcher("RegistredUserHomePageForMembers.jsp").forward(request, response);
							return;
						}
					}else if(intTargetPersonID == null){
						request.getRequestDispatcher("RegistredUserHomePageForMembers.jsp").forward(request, response);
						return;
					}	
				}else if(selectedPerson == null){
					request.getRequestDispatcher("RegistredUserHomePageForMembers.jsp").forward(request, response);
					return;
				}
			}else if(loggedUser == null){
				request.getRequestDispatcher("Welcome.jsp").forward(request, response);
				return;
			}
		}else if(intSelectedPersonID == null){
			request.getRequestDispatcher("RegistredUserHomePageForMembers.jsp").forward(request, response);
			return;
		}	
	}

	//--------------------------------------------------------------------------------------------------------------------------------------------------
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}


}
